// src/router.js
const express = require('express')
//给req增加一个cookies属性
const cookieParser = require('cookie-parser')
//给req增加一个body属性
const bodyParser = require('body-parser')
//文件写入和读取用
const fs = require('fs')
const router = express.Router()
router.use(bodyParser.urlencoded({extended:false}))
router.use(cookieParser())

//test路由
router.get('/test',(req,res)=>{
  fs.readFile(`${__dirname}/homework/s1.json`,(err,data)=>{
    res.send(`var data = ${data}`);
  });
});

//abc路由
router.get('/abc',(req,res)=>{
  res.send(req.query);
});

router.post('/abc', (req, res) => {
  res.send(req.body); 
});

//user路由
router.get('/user',(req,res)=>{
  let id = req.query.id;
  res.sendFile(`${__dirname}/homework/${id}.json`);
});

router.post('/user', (req, res) => {
  let data = req.body.changeStr;
  fs.writeFile(`${__dirname}/homework/s1.json`,data,()=>{
    res.send('change successfully~!');
  });
});
//接口，用来把router传递出去
module.exports=router